package com.weiyin.examination.course;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.chad.library.adapter.base.BaseViewHolder;
import com.weiyin.examination.R;
import com.weiyin.examination.adapter.CourseA1Adapter;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.dialog.CourseA1Dialog;
import com.weiyin.examination.dialog.CourseDialog;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.view.GridLayoutManager;
import com.weiyin.examination.view.RoundProgressBar;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

///**
// * @author njf
// *         Created by lenovo on 2017/9/18.
// */

public class CourseA1 extends Course implements CourseA1Adapter.OnItemClickInterface {
    private View rootView;
    private Activity activity;
    private ClickAble clickAble;

    private RecyclerView courseA1RecyclerView;

    private CourseA1Adapter courseA1Adapter;
    private ImageView course1LayoutPlay;
    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView,
            titleLayoutSubjectScoreTextView, titleLayoutNumberTextView, titleTicketNumber, courseA1TextView;
    private RelativeLayout titleLayoutNumberRl, courseA1Play;

    private RoundProgressBar course1LayoutProgressBar;
    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private MediaPlayer mediaPlayer;
    private AnimationDrawable animationDrawable;

    private int mediaIndex = 0, courseIndex, stopIndex = 0;

    private Handler mHandler = new Handler();

    private LayoutHelper layoutHelper;

    private Map<String, String> map;
    private CourseDialog courseDialog;
    private int viewId;

    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea1_layout, null);
            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);
            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            map = new HashMap<>();
            clickAble = new ClickAble();
            mediaPlayer = new MediaPlayer();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
        }
    }

    @Override
    public void initView() {
        courseA1TextView = (TextView) rootView.findViewById(R.id.courseA1TextView);
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);

        courseA1Play = (RelativeLayout) rootView.findViewById(R.id.courseA1Play);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);

        courseA1RecyclerView = (RecyclerView) rootView.findViewById(R.id.courseA1RecyclerView);
        course1LayoutPlay = (ImageView) rootView.findViewById(R.id.course1LayoutPlay);
        course1LayoutProgressBar = (RoundProgressBar) rootView.findViewById(R.id.course1LayoutProgressBar);
        courseA1Adapter = new CourseA1Adapter(activity, R.layout.coursea1_item_layout, answerModuleList);
        courseA1RecyclerView.setLayoutManager(new GridLayoutManager(activity, getLineSize(), LinearLayoutManager.VERTICAL, false));
        courseA1RecyclerView.setAdapter(courseA1Adapter);
        courseA1Adapter.setOnItemClickInterface(this);

        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
    }

    private void initViewData() {
        if (testModule != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (stopIndex < Constant.MEDIA_PLAYER_STOP_NUMBER && mediaIndex < testModule.getMp3UrlList().size()) {
                        mediaPlayerPlay();
                    }
                    mHandler.removeCallbacks(this);
                }
            }, 5000);

            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());
            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);
            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
        }
    }

    private int getLineSize() {
        int size = 0;
        if (answerModuleList != null) {
            size = answerModuleList.size() / 2;
        }
        return size;
    }

    private void mediaPlayerPlay() {
        try {
            if (mediaPlayer == null) return;
            mediaPlayer.reset();
            LogUtil.i(TAG, RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url());
            mediaPlayer.setDataSource(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""));
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    courseA1TextView.setText("第" + (mediaIndex + 1) + "题，第" + (stopIndex + 1) + "遍，共三遍");
                    mp.start();
                    course1LayoutProgressBar.setMax(mediaPlayer.getDuration());
                    mHandler.post(updateThread);
                    course1LayoutPlay.setImageResource(R.drawable.audio_pause_bg);
                    animationDrawable = new AnimationDrawable();
                    animationDrawable = (AnimationDrawable) course1LayoutPlay.getDrawable();
                    animationDrawable.start();
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        if (mediaIndex < testModule.getMp3UrlList().size()) {
                            LogUtil.i(TAG, "stop=" + stopIndex + " media=" + mediaIndex + " RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url()=" + RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url());
                            stopIndex++;
                            if (stopIndex == Constant.MEDIA_PLAYER_STOP_NUMBER) {
                                mediaIndex++;
                                stopIndex = 0;
                            }
                            mp.reset();
                            if (mediaIndex == testModule.getMp3UrlList().size() || testModule.getMp3UrlList().get(mediaIndex).getMp3Url() == null) {
                                mediaIndex = testModule.getMp3UrlList().size();
                                mHandler.removeCallbacks(updateThread);
                                mediaRelease();
                                course1LayoutPlay.setImageResource(R.drawable.audio_play);
                                course1LayoutProgressBar.setProgress(0);
                            } else {
                                mp.setDataSource(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""));
                                mp.prepare();
                            }
                        } else {
                            mHandler.removeCallbacks(updateThread);
                            mediaRelease();
                            course1LayoutPlay.setImageResource(R.drawable.audio_play);
                            course1LayoutProgressBar.setProgress(0);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaPlayerStop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(updateThread);
        }
        if (animationDrawable != null) {
            animationDrawable.stop();
            course1LayoutPlay.setImageResource(R.drawable.audio_play);
        }
        if (course1LayoutProgressBar != null) {
            course1LayoutProgressBar.setProgress(0);
        }
    }

    private void mediaRelease() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        courseA1TextView.setText("听力播放结束");
    }

    /**
     * update进度条
     */
    private Runnable updateThread = new Runnable() {
        @Override
        public void run() {
            try {
                if (mediaPlayer != null) {
                    if (mediaPlayer.getCurrentPosition() == mediaPlayer.getDuration()) {
                        return;
                    }
                    course1LayoutProgressBar.setProgress(mediaPlayer.getCurrentPosition());
                }
                mHandler.removeCallbacks(updateThread);
                mHandler.postDelayed(updateThread, 50);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onItemClick(BaseViewHolder holder, int position) {
        showDialog(holder, position);
    }

    private void showDialog(final BaseViewHolder holder, final int position) {
        CourseA1Dialog courseA1Dialog;
        int x = (int) holder.getView(R.id.courseA1ItemLayout).getX() + holder.getView(R.id.courseA1ItemLayout).getWidth() / 2;
        int y = holder.getView(R.id.courseA1ItemLayout).getBottom() + courseA1RecyclerView.getTop();
        courseA1Dialog = new CourseA1Dialog(activity, R.style.BlueToothDialogStyle, testModule);
        Window window = courseA1Dialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();

        p.x = x - d.getWidth() / 2 + layoutHelper.scaleDimension(100, "x");
        p.y = y - (d.getHeight() / 2 - layoutHelper.scaleDimension(230 + 150, "y") / 2);
        window.setAttributes(p);
        courseA1Dialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                if (!StringUtils.isEmpty(result)) {
                    if (Constant.CENTER.equals(type)) {
                        if (result.contains(Constant.INTERVAL_SIGN)) {
                            int index = result.indexOf(Constant.INTERVAL_SIGN);
                            holder.setText(R.id.courseA1ItemTextView1, result.substring(0, index) + "\n" + result.substring(index + 1));
                        } else {
                            holder.setText(R.id.courseA1ItemTextView1, result);
                        }
                        map.put(position + Constant.CENTER, answerId);
                    } else if (Constant.LEFT.equals(type)) {
                        if (result.contains(Constant.INTERVAL_SIGN)) {
                            int index = result.indexOf(Constant.INTERVAL_SIGN);
                            holder.setText(R.id.courseA1ItemTextView1, result.substring(0, index) + "\n" + result.substring(index + 1));
                        } else {
                            holder.setText(R.id.courseA1ItemTextView1, result);
                        }
                        map.put(position + Constant.LEFT, answerId);
                    } else if (Constant.RIGHT.equals(type)) {
                        if (result.contains(Constant.INTERVAL_SIGN)) {
                            int index = result.indexOf(Constant.INTERVAL_SIGN);
                            LogUtil.i(TAG, result.substring(0, result.indexOf(Constant.INTERVAL_SIGN)));
                            holder.setText(R.id.courseA1ItemTextView2, result.substring(0, index) + "\n" + result.substring(index + 1));
                        } else {
                            holder.setText(R.id.courseA1ItemTextView2, result);
                        }
                        map.put(position + Constant.RIGHT, answerId);
                    }
                }
            }
        });
        if (activity.hasWindowFocus()) {
            courseA1Dialog.show();
        }
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (mediaIndex >= testModule.getMp3UrlList().size()) {
                switch (v.getId()) {
                    case R.id.titleLayoutNextTextView:
                        next();
                        break;
                    case R.id.titleLayoutLastTextView:
                        last();
                        break;
                    case R.id.courseA1Play:
//                    mediaPlayerPlay();
                        break;
                    case R.id.titleLayoutNumberRl:
                        skip();
                        break;
                    default:

                        break;
                }
            } else {
                if (resultMap()) {
                    //答完题目
                    viewId = v.getId();
                    showDialog();
                } else {
                    Constant.showTextToast(activity, "答完本题后方可进入下一题");
                }
            }
        }
    }

    private void next() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
        mediaPlayerStop();
    }

    private void last() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
        mediaPlayerStop();
    }

    private void skip() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        dialogShowListener.dialogShow(0, courseIndex, resultMap());
        mediaPlayerStop();
    }

    private void showDialog() {
        if (courseDialog == null) {
            String txt = activity.getResources().getString(R.string.courseText);
            courseDialog = new CourseDialog(activity, R.style.BlueToothDialogStyle, txt);
        }
        if (!courseDialog.isShowing()) {
            courseDialog.show();
        }
        courseDialog.setCourseDialogInterlisteren(new CourseDialog.CourseDialogListener() {
            @Override
            public void courseDialogResult(int type) {
                if (type == 1) {
                    mediaIndex = testModule.getMp3UrlList().size();
                    courseA1TextView.setText("听力播放结束");
                    if (viewId == R.id.titleLayoutNextTextView) {
                        next();
                    } else if (viewId == R.id.titleLayoutLastTextView) {
                        last();
                    } else if (viewId == R.id.titleLayoutNumberRl) {
                        skip();
                    }
                }
            }
        });
    }

    private boolean resultMap() {
        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1), SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1));
        if (map != null) {
            boolean result = false;
            int index = 0;
            score = 0;
            for (int i = 0; i < answerModuleList.size(); i++) {
                if (map.get(i + Constant.CENTER) != null || map.get(i + Constant.LEFT) != null || map.get(i + Constant.RIGHT) != null) {
                    if (map.get(i + Constant.CENTER) != null && map.get(i + Constant.CENTER).equals(answerModuleList.get(i).getCenterId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore());
                    }

                    if (map.get(i + Constant.LEFT) != null && map.get(i + Constant.LEFT).equals(answerModuleList.get(i).getLeftId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore()) / 2;
                    }

                    if (map.get(i + Constant.RIGHT) != null && map.get(i + Constant.RIGHT).equals(answerModuleList.get(i).getRightId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore()) / 2;
                    }
                    index++;
                }
            }
            LogUtil.i(TAG, "score=" + score);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA1.class.getSimpleName(), score + "");
            if (index == answerModuleList.size()) {
                result = true;
            }
            return result;
        } else {
            LogUtil.i(TAG, "score=" + 0);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA1.class.getSimpleName(), "0");
            return false;
        }
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {
        mediaPlayerStop();
    }

    @Override
    public void destroy() {
        if (mHandler != null) {
            mHandler.removeCallbacks(updateThread);
        }
        mediaRelease();
        if (animationDrawable != null) {
            animationDrawable = null;
        }
    }
}
